package org.apache.ocean.util;

import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;

/**
 *
 * @author jasonr
 */
public class ConcurrentWeakHashMap<K,V> {
  public WeakHashMap<K,V> map;
  public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

  public ConcurrentWeakHashMap() {
  	map = new WeakHashMap<K,V>();
  }
  
  public V putIfAbsent(K key, V value) {
    lock.writeLock().lock();
    try {
      V existingValue = map.get(key);
      if (existingValue != null) return existingValue;
      map.put(key, value);
      return value;
    } finally {
      lock.writeLock().unlock();
    }
  }
  
  public V get(Object key) {
    lock.readLock().lock();
    try {
      return map.get(key);
    } finally {
      lock.readLock().unlock();
    }
  }
  
  public void remove(K key) {
    lock.writeLock().lock();
    try {
      map.remove(key);
    } finally {
      lock.writeLock().unlock();
    }
  }
  
  public void put(K key, V value) {
    lock.writeLock().lock();
    try {
      map.put(key, value);
    } finally {
      lock.writeLock().unlock();
    }
  }
  
}
